package com.xjc.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjc.business.entity.domain.SysAdmins;
import com.xjc.business.entity.po.sysadmin.SysAdminLoginPo;
import com.xjc.business.entity.vo.sysadmin.SysAdminLoginVo;
import com.xjc.business.service.SysAdminsService;
import com.xjc.business.mapper.SysAdminsMapper;
import com.xjc.system.constants.MyConstants;
import com.xjc.system.exception.MyException;
import com.xjc.system.result.Result;
import com.xjc.system.result.ResultCode;
import com.xjc.system.utils.TokenUtils;
import org.springframework.stereotype.Service;

/**
* @author root
* @description 针对表【sys_admins(系统管理员表)】的数据库操作Service实现
* @createDate 2025-01-25 10:24:33
*/
@Service
public class SysAdminsServiceImpl extends ServiceImpl<SysAdminsMapper, SysAdmins>
    implements SysAdminsService {

    /**
     * 登录
     *
     * @param sysAdminLoginPo 登录参数
     * @return 登录成功返回token，失败返回错误信息
     */
    @Override
    public Result<SysAdminLoginVo> doLogin(SysAdminLoginPo sysAdminLoginPo) {

        String username = sysAdminLoginPo.getUsername();
        String password = sysAdminLoginPo.getPassword();

        LambdaQueryWrapper<SysAdmins> sysAdminsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysAdminsLambdaQueryWrapper.eq(SysAdmins::getUsername, username);

        SysAdmins sysAdminsFromDB = getOne(sysAdminsLambdaQueryWrapper);

        if (sysAdminsFromDB == null){
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.USERNAME_ERROR);
        }

        if (!(password.equals(sysAdminsFromDB.getPassword()))){
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.PASSWORD_ERROR);
        }

        SysAdminLoginVo sysAdminLoginVo = new SysAdminLoginVo();
        sysAdminLoginVo.setId(sysAdminsFromDB.getId());
        sysAdminLoginVo.setUsername(sysAdminsFromDB.getUsername());
        sysAdminLoginVo.setNickname(sysAdminsFromDB.getNickname());
        sysAdminLoginVo.setPic(sysAdminsFromDB.getPic());
        sysAdminLoginVo.setToken(TokenUtils.generateToken(sysAdminsFromDB.getId()));

        return Result.okWithData(sysAdminLoginVo);
    }
}




